#include "../include/cli_manager.h"
#include "logger.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <chrono>
#include <ctime>
#include <json/json.h>

// 构造函数
CliManager::CliManager(const std::string& etcdUrl)
    : m_etcdUrl(etcdUrl) {
    LOG_DEBUG("创建CLI管理器: etcdUrl=" + etcdUrl);
}

// 析构函数
CliManager::~CliManager() {
    LOG_DEBUG("销毁CLI管理器");
    
    // 停止所有节点
    for (auto it = m_nodes.begin(); it != m_nodes.end(); ++it) {
        LOG_INFO("停止节点: " + it->first);
        it->second->stop();
        delete it->second;
    }
    
    m_nodes.clear();
}

// 运行命令行
void CliManager::run() {
    LOG_INFO("启动CLI管理器");
    
    // 加载持久化节点
    loadPersistentNodes();
    
    std::string command;
    bool running = true;
    
    // 显示欢迎信息
    std::cout << std::endl;
    std::cout << "===== ETCD 多节点管理器 =====" << std::endl;
    std::cout << "输入 'help' 获取可用命令列表" << std::endl;
    std::cout << std::endl;
    
    // 命令处理循环
    while (running) {
        std::cout << "> ";
        std::getline(std::cin, command);
        
        if (command.empty()) {
            continue;
        }
        
        LOG_DEBUG("收到命令: " + command);
        
        // 处理命令
        if (command == "exit" || command == "quit") {
            running = false;
            LOG_INFO("收到退出命令");
        } else {
            try {
                processCommand(command);
            } catch (const std::exception& e) {
                LOG_ERROR("处理命令异常: " + std::string(e.what()));
                std::cerr << "命令处理错误: " << e.what() << std::endl;
            }
        }
    }
    
    LOG_INFO("CLI管理器退出");
}

// 显示帮助信息
void CliManager::showHelp() {
    std::cout << "可用命令:" << std::endl;
    std::cout << "  help               - 显示此帮助信息" << std::endl;
    std::cout << "  create <id> <ep>   - 创建新节点 (id:节点ID, ep:节点终端)" << std::endl;
    std::cout << "  delete <id> [-k]   - 删除节点 (id:节点ID, -k:保留持久化信息)" << std::endl;
    std::cout << "  list               - 列出所有节点" << std::endl;
    std::cout << "  leader             - 显示当前主节点" << std::endl;
    std::cout << "  fault <id>         - 模拟节点故障 (id:节点ID)" << std::endl;
    std::cout << "  recover <id>       - 模拟节点恢复 (id:节点ID)" << std::endl;
    std::cout << "  exit/quit          - 退出程序" << std::endl;
    std::cout << std::endl;
    std::cout << "说明：" << std::endl;
    std::cout << "  节点信息会被持久化存储，即使程序退出后重启，之前的节点信息也会保留" << std::endl;
    std::cout << "  默认情况下，delete命令会完全删除节点（包括持久化信息）" << std::endl;
    std::cout << "  如果只想临时删除节点，保留持久化信息，请使用 'delete <id> -k' 或 'delete <id> --keep-persistent'" << std::endl;
}

// 创建节点
void CliManager::createNode(const std::string& nodeId, const std::string& endpoint) {
    LOG_INFO("创建节点: nodeId=" + nodeId + ", endpoint=" + endpoint);
    
    // 检查节点是否已存在
    if (m_nodes.find(nodeId) != m_nodes.end()) {
        LOG_WARNING("节点已存在: " + nodeId);
        std::cout << "节点 " << nodeId << " 已存在" << std::endl;
        return;
    }
    
    try {
        // 创建节点
        NodeManager* nodeManager = new NodeManager(m_etcdUrl, nodeId, endpoint);
        
        // 初始化节点
        if (!nodeManager->init()) {
            LOG_ERROR("初始化节点失败: " + nodeId);
            std::cout << "初始化节点失败: " << nodeId << std::endl;
            delete nodeManager;
            return;
        }
        
        // 注册状态变更回调
        nodeManager->registerStatusCallback([nodeId](NodeStatus oldStatus, NodeStatus newStatus) {
            LOG_INFO("节点状态变更: " + nodeId + ", 从 " + std::to_string(static_cast<int>(oldStatus)) +
                     " 到 " + std::to_string(static_cast<int>(newStatus)));
            
            std::string oldStatusStr = "未知";
            std::string newStatusStr = "未知";
            
            switch (oldStatus) {
                case NodeStatus::FOLLOWER: oldStatusStr = "从节点"; break;
                case NodeStatus::LEADER: oldStatusStr = "主节点"; break;
                case NodeStatus::FAULT: oldStatusStr = "故障"; break;
                default: break;
            }
            
            switch (newStatus) {
                case NodeStatus::FOLLOWER: newStatusStr = "从节点"; break;
                case NodeStatus::LEADER: newStatusStr = "主节点"; break;
                case NodeStatus::FAULT: newStatusStr = "故障"; break;
                default: break;
            }
            
            std::cout << std::endl << "节点 " << nodeId << " 状态从 " 
                      << oldStatusStr << " 变为 " << newStatusStr << std::endl << "> ";
            std::cout.flush();
        });
        
        // 启动节点
        if (!nodeManager->start()) {
            LOG_ERROR("启动节点失败: " + nodeId);
            std::cout << "启动节点失败: " << nodeId << std::endl;
            delete nodeManager;
            return;
        }
        
        // 保存节点
        m_nodes[nodeId] = nodeManager;
        
        LOG_INFO("节点创建并启动成功: " + nodeId);
        std::cout << "成功创建并启动节点 " << nodeId << " (endpoint: " << endpoint << ")" << std::endl;
    } catch (const std::exception& e) {
        LOG_ERROR("创建节点异常: " + std::string(e.what()));
        std::cout << "创建节点时发生错误: " << e.what() << std::endl;
    }
}

// 删除节点
void CliManager::deleteNode(const std::string& nodeId, bool removePersistent) {
    LOG_INFO("删除节点: " + nodeId + (removePersistent ? "" : " (保留持久化信息)"));
    
    // 检查节点是否存在
    auto it = m_nodes.find(nodeId);
    if (it == m_nodes.end()) {
        LOG_WARNING("节点不存在: " + nodeId);
        std::cout << "节点 " << nodeId << " 不存在" << std::endl;
        return;
    }
    
    try {
        // 停止节点
        it->second->stop();
        
        // 如果需要删除持久化信息
        if (removePersistent) {
            LOG_INFO("删除节点持久化信息: " + nodeId);
            std::cout << "正在删除节点 " << nodeId << " 的持久化信息..." << std::endl;
            
            try {
                // 构建持久化节点的键
                std::string persistentKey = "/persistent_nodes/" + nodeId;
                
                // 使用ETCD客户端删除持久化信息
                EtcdClient etcdClient(m_etcdUrl);
                if (etcdClient.init()) {
                    EtcdResult result = etcdClient.del(persistentKey);
                    if (result.success) {
                        std::cout << "已删除节点 " << nodeId << " 的持久化信息" << std::endl;
                    } else {
                        LOG_WARNING("删除持久化信息失败: " + result.errorMessage);
                        std::cout << "删除持久化信息失败: " << result.errorMessage << std::endl;
                    }
                } else {
                    LOG_ERROR("初始化ETCD客户端失败");
                    std::cout << "无法连接ETCD服务器" << std::endl;
                }
            } catch (const std::exception& e) {
                LOG_ERROR("删除持久化信息异常: " + std::string(e.what()));
                std::cout << "删除持久化信息时发生错误: " << e.what() << std::endl;
            }
        } else {
            LOG_INFO("保留节点持久化信息: " + nodeId);
            std::cout << "节点 " << nodeId << " 的持久化信息已保留，重启后节点将自动恢复" << std::endl;
        }
        
        // 删除节点
        delete it->second;
        m_nodes.erase(it);
        
        LOG_INFO("节点删除成功: " + nodeId);
        std::cout << "成功删除节点 " << nodeId << std::endl;
    } catch (const std::exception& e) {
        LOG_ERROR("删除节点异常: " + std::string(e.what()));
        std::cout << "删除节点时发生错误: " << e.what() << std::endl;
    }
}

// 列出所有节点
void CliManager::listNodes() {
    LOG_INFO("列出所有节点");
    
    try {
        // 获取所有节点
        std::vector<NodeInfo> allNodes;
        
        // 先添加本地节点
        for (const auto& node : m_nodes) {
            allNodes.push_back(node.second->getCurrentNodeInfo());
        }
        
        // 如果没有节点，添加远程节点
        if (!m_nodes.empty()) {
            // 获取远程节点
            std::vector<NodeInfo> remoteNodes = m_nodes.begin()->second->getAllNodes();
            
            // 合并本地节点和远程节点
            for (const auto& remoteNode : remoteNodes) {
                bool found = false;
                for (const auto& localNode : allNodes) {
                    if (remoteNode.id == localNode.id) {
                        found = true;
                        break;
                    }
                }
                
                if (!found) {
                    allNodes.push_back(remoteNode);
                }
            }
        }
        
        // 按节点ID排序
        std::sort(allNodes.begin(), allNodes.end(), [](const NodeInfo& a, const NodeInfo& b) {
            return a.id < b.id;
        });
        
        // 显示节点信息
        std::cout << "===== 节点列表 =====" << std::endl;
        std::cout << std::left << std::setw(17) << "节点ID" 
                  << std::setw(20) << "Endpoint" 
                  << std::setw(10) << "状态" 
                  << std::setw(25) << "加入时间" 
                  << std::setw(25) << "最后心跳" << std::endl;
        std::cout << "-------------------------------------------------------------------------------------------------------" << std::endl;
        
        for (const auto& node : allNodes) {
            // 将时间戳转换为本地时间
            auto to_localtime = [](const std::chrono::system_clock::time_point& tp) -> std::string {
                auto time_t = std::chrono::system_clock::to_time_t(tp);
                auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
                    tp.time_since_epoch()).count() % 1000;
                
                std::stringstream ss;
                ss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S") 
                   << '.' << std::setfill('0') << std::setw(3) << ms;
                return ss.str();
            };
            
            std::string statusStr = "未知";
            switch (node.status) {
                case NodeStatus::FOLLOWER: statusStr = "从节点"; break;
                case NodeStatus::LEADER: statusStr = "主节点"; break;
                case NodeStatus::FAULT: statusStr = "故障"; break;
                default: break;
            }
            
            std::cout << std::left << std::setw(17) << node.id 
                      << std::setw(20) << node.endpoint 
                      << std::setw(10) << statusStr 
                      << std::setw(25) << to_localtime(node.joinTime) 
                      << std::setw(25) << to_localtime(node.lastHeartbeat) << std::endl;
        }
        
        std::cout << "===================" << std::endl;
        
        LOG_INFO("显示节点列表成功，共" + std::to_string(allNodes.size()) + "个节点");
    } catch (const std::exception& e) {
        LOG_ERROR("列出节点异常: " + std::string(e.what()));
        std::cout << "列出节点时发生错误: " << e.what() << std::endl;
    }
}

// 显示主节点
void CliManager::showLeader() {
    LOG_INFO("显示主节点");
    
    try {
        // 如果没有节点，显示错误
        if (m_nodes.empty()) {
            LOG_WARNING("没有节点可查询");
            std::cout << "没有节点可查询" << std::endl;
            return;
        }
        
        // 获取主节点
        NodeInfo leaderNode = m_nodes.begin()->second->getLeaderNode();
        
        if (leaderNode.status != NodeStatus::LEADER) {
            LOG_WARNING("当前没有主节点");
            std::cout << "当前没有主节点" << std::endl;
            return;
        }
        
        // 将时间戳转换为本地时间
        auto to_localtime = [](const std::chrono::system_clock::time_point& tp) -> std::string {
            auto time_t = std::chrono::system_clock::to_time_t(tp);
            auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
                tp.time_since_epoch()).count() % 1000;
            
            std::stringstream ss;
            ss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S") 
               << '.' << std::setfill('0') << std::setw(3) << ms;
            return ss.str();
        };
        
        // 显示主节点信息
        std::cout << "===== 主节点信息 =====" << std::endl;
        std::cout << "节点ID: " << leaderNode.id << std::endl;
        std::cout << "Endpoint: " << leaderNode.endpoint << std::endl;
        std::cout << "加入时间: " << to_localtime(leaderNode.joinTime) << std::endl;
        std::cout << "最后心跳: " << to_localtime(leaderNode.lastHeartbeat) << std::endl;
        std::cout << "======================" << std::endl;
        
        LOG_INFO("显示主节点成功: " + leaderNode.id);
    } catch (const std::exception& e) {
        LOG_ERROR("显示主节点异常: " + std::string(e.what()));
        std::cout << "显示主节点时发生错误: " << e.what() << std::endl;
    }
}

// 模拟节点故障
void CliManager::simulateFault(const std::string& nodeId) {
    LOG_INFO("模拟节点故障: " + nodeId);
    
    // 检查节点是否存在
    auto it = m_nodes.find(nodeId);
    if (it == m_nodes.end()) {
        LOG_WARNING("节点不存在: " + nodeId);
        std::cout << "节点 " << nodeId << " 不存在" << std::endl;
        return;
    }
    
    try {
        // 模拟故障
        if (it->second->simulateFault()) {
            LOG_INFO("模拟节点故障成功: " + nodeId);
            std::cout << "成功模拟节点 " << nodeId << " 故障" << std::endl;
        } else {
            LOG_ERROR("模拟节点故障失败: " + nodeId);
            std::cout << "模拟节点 " << nodeId << " 故障失败" << std::endl;
        }
    } catch (const std::exception& e) {
        LOG_ERROR("模拟节点故障异常: " + std::string(e.what()));
        std::cout << "模拟节点故障时发生错误: " << e.what() << std::endl;
    }
}

// 模拟节点恢复
void CliManager::simulateRecover(const std::string& nodeId) {
    LOG_INFO("模拟节点恢复: " + nodeId);
    
    // 检查节点是否存在
    auto it = m_nodes.find(nodeId);
    if (it == m_nodes.end()) {
        LOG_WARNING("节点不存在: " + nodeId);
        std::cout << "节点 " << nodeId << " 不存在" << std::endl;
        return;
    }
    
    try {
        // 模拟恢复
        if (it->second->simulateRecover()) {
            LOG_INFO("模拟节点恢复成功: " + nodeId);
            std::cout << "成功模拟节点 " << nodeId << " 恢复" << std::endl;
        } else {
            LOG_ERROR("模拟节点恢复失败: " + nodeId);
            std::cout << "模拟节点 " << nodeId << " 恢复失败" << std::endl;
        }
    } catch (const std::exception& e) {
        LOG_ERROR("模拟节点恢复异常: " + std::string(e.what()));
        std::cout << "模拟节点恢复时发生错误: " << e.what() << std::endl;
    }
}

// 处理命令
void CliManager::processCommand(const std::string& command) {
    LOG_DEBUG("处理命令: " + command);
    
    std::istringstream iss(command);
    std::string cmd;
    iss >> cmd;
    
    if (cmd == "help") {
        showHelp();
    } else if (cmd == "create") {
        std::string nodeId, endpoint;
        if (!(iss >> nodeId >> endpoint)) {
            LOG_WARNING("create命令参数不足");
            std::cout << "用法: create <nodeId> <endpoint>" << std::endl;
            return;
        }
        createNode(nodeId, endpoint);
    } else if (cmd == "delete") {
        std::string nodeId;
        std::string option;
        bool removePersistent = true;  // 默认为true，删除持久化信息
        
        if (!(iss >> nodeId)) {
            LOG_WARNING("delete命令参数不足");
            std::cout << "用法: delete <nodeId> [--keep-persistent|-k]" << std::endl;
            return;
        }
        
        // 检查是否有额外选项
        iss >> option;
        if (option == "--keep-persistent" || option == "-k") {
            removePersistent = false;  // 如果指定了保留选项，则不删除持久化信息
        }
        
        deleteNode(nodeId, removePersistent);
    } else if (cmd == "list") {
        listNodes();
    } else if (cmd == "leader") {
        showLeader();
    } else if (cmd == "fault") {
        std::string nodeId;
        if (!(iss >> nodeId)) {
            LOG_WARNING("fault命令参数不足");
            std::cout << "用法: fault <nodeId>" << std::endl;
            return;
        }
        simulateFault(nodeId);
    } else if (cmd == "recover") {
        std::string nodeId;
        if (!(iss >> nodeId)) {
            LOG_WARNING("recover命令参数不足");
            std::cout << "用法: recover <nodeId>" << std::endl;
            return;
        }
        
        // 检查节点是否存在于内存中
        auto it = m_nodes.find(nodeId);
        if (it != m_nodes.end()) {
            // 节点在内存中，直接恢复
            simulateRecover(nodeId);
        } else {
            // 节点不在内存中，尝试从持久化存储恢复
            LOG_INFO("节点 " + nodeId + " 不在内存中，尝试从持久化存储恢复");
            if (!recoverFaultNode(nodeId)) {
                LOG_WARNING("从持久化存储恢复节点 " + nodeId + " 失败");
                std::cout << "节点 " << nodeId << " 不存在或无法从持久化存储恢复" << std::endl;
            }
        }
    } else {
        LOG_WARNING("未知命令: " + cmd);
        std::cout << "未知命令: " << cmd << "，输入 'help' 获取帮助" << std::endl;
    }
}

// 实现loadPersistentNodes方法
void CliManager::loadPersistentNodes() {
    LOG_INFO("开始加载持久化节点");
    
    try {
        // 创建临时ETCD客户端
        EtcdClient etcdClient(m_etcdUrl);
        if (!etcdClient.init()) {
            LOG_ERROR("初始化ETCD客户端失败，无法加载持久化节点");
            return;
        }
        
        // 获取所有持久化节点信息
        EtcdResult result = etcdClient.getPrefix("/persistent_nodes/");
        if (!result.success) {
            LOG_WARNING("获取持久化节点列表失败: " + result.errorMessage);
            return;
        }
        
        LOG_INFO("发现 " + std::to_string(result.kvs.size()) + " 个持久化节点记录");
        
        if (result.kvs.empty()) {
            LOG_INFO("没有持久化节点需要加载");
            return;
        }
        
        // 遍历所有持久化节点
        for (const auto& kv : result.kvs) {
            try {
                // 从键中提取节点ID
                std::string nodeKey = kv.first;
                std::string nodeId = nodeKey.substr(nodeKey.find_last_of('/') + 1);
                
                // 解析节点信息JSON
                Json::Value root;
                Json::Reader reader;
                
                if (!reader.parse(kv.second, root)) {
                    LOG_WARNING("解析持久化节点JSON失败: " + kv.second);
                    continue;
                }
                
                // 提取节点终端点
                std::string endpoint = root["endpoint"].asString();
                
                // 检查节点状态
                NodeStatus nodeStatus = NodeStatus::UNKNOWN;
                if (root.isMember("status")) {
                    nodeStatus = static_cast<NodeStatus>(root["status"].asInt());
                }
                
                // 获取状态描述
                std::string statusDesc = "未知";
                switch (nodeStatus) {
                    case NodeStatus::FOLLOWER: statusDesc = "从节点"; break;
                    case NodeStatus::LEADER: statusDesc = "主节点"; break;
                    case NodeStatus::FAULT: statusDesc = "故障"; break;
                    default: break;
                }
                
                // 检查是否已经在本地加载了这个节点
                if (m_nodes.find(nodeId) != m_nodes.end()) {
                    LOG_INFO("节点 " + nodeId + " 已经在本地加载，跳过");
                    continue;
                }
                
                // 显示节点状态
                LOG_INFO("发现持久化节点: " + nodeId + ", endpoint: " + endpoint + ", 状态: " + statusDesc);
                
                // 对于故障节点，只显示信息但不加载
                if (nodeStatus == NodeStatus::FAULT) {
                    std::cout << "发现故障节点: " << nodeId << ", endpoint: " << endpoint 
                              << " (未加载，状态: 故障)" << std::endl;
                    continue;
                }
                
                // 创建并启动正常节点
                LOG_INFO("加载持久化节点: " + nodeId + ", endpoint: " + endpoint);
                std::cout << "加载持久化节点: " << nodeId << ", endpoint: " << endpoint << std::endl;
                
                // 创建节点
                NodeManager* nodeManager = new NodeManager(m_etcdUrl, nodeId, endpoint);
                
                // 初始化节点
                if (!nodeManager->init()) {
                    LOG_ERROR("初始化持久化节点失败: " + nodeId);
                    delete nodeManager;
                    continue;
                }
                
                // 注册状态变更回调
                nodeManager->registerStatusCallback([nodeId](NodeStatus oldStatus, NodeStatus newStatus) {
                    LOG_INFO("节点状态变更: " + nodeId + ", 从 " + std::to_string(static_cast<int>(oldStatus)) +
                             " 到 " + std::to_string(static_cast<int>(newStatus)));
                    
                    std::string oldStatusStr = "未知";
                    std::string newStatusStr = "未知";
                    
                    switch (oldStatus) {
                        case NodeStatus::FOLLOWER: oldStatusStr = "从节点"; break;
                        case NodeStatus::LEADER: oldStatusStr = "主节点"; break;
                        case NodeStatus::FAULT: oldStatusStr = "故障"; break;
                        default: break;
                    }
                    
                    switch (newStatus) {
                        case NodeStatus::FOLLOWER: newStatusStr = "从节点"; break;
                        case NodeStatus::LEADER: newStatusStr = "主节点"; break;
                        case NodeStatus::FAULT: newStatusStr = "故障"; break;
                        default: break;
                    }
                    
                    std::cout << std::endl << "节点 " << nodeId << " 状态从 " 
                              << oldStatusStr << " 变为 " << newStatusStr << std::endl << "> ";
                    std::cout.flush();
                });
                
                // 启动节点
                if (!nodeManager->start()) {
                    LOG_ERROR("启动持久化节点失败: " + nodeId);
                    delete nodeManager;
                    continue;
                }
                
                // 保存节点
                m_nodes[nodeId] = nodeManager;
                LOG_INFO("成功加载并启动持久化节点: " + nodeId);
            } catch (const std::exception& e) {
                LOG_ERROR("处理持久化节点异常: " + std::string(e.what()));
            }
        }
        
        LOG_INFO("持久化节点加载完成，共成功加载 " + std::to_string(m_nodes.size()) + " 个节点");
    } catch (const std::exception& e) {
        LOG_ERROR("加载持久化节点异常: " + std::string(e.what()));
    }
}

// 从持久化存储恢复故障节点
bool CliManager::recoverFaultNode(const std::string& nodeId) {
    LOG_INFO("尝试从持久化存储恢复故障节点: " + nodeId);
    
    try {
        // 创建临时ETCD客户端
        EtcdClient etcdClient(m_etcdUrl);
        if (!etcdClient.init()) {
            LOG_ERROR("初始化ETCD客户端失败，无法恢复故障节点");
            std::cout << "无法连接ETCD服务器" << std::endl;
            return false;
        }
        
        // 获取持久化节点信息
        std::string persistentKey = "/persistent_nodes/" + nodeId;
        EtcdResult result = etcdClient.get(persistentKey);
        if (!result.success) {
            LOG_WARNING("获取持久化节点信息失败: " + result.errorMessage);
            std::cout << "获取持久化节点信息失败: " << result.errorMessage << std::endl;
            return false;
        }
        
        if (result.value.empty()) {
            LOG_WARNING("节点 " + nodeId + " 的持久化信息不存在");
            std::cout << "节点 " << nodeId << " 的持久化信息不存在" << std::endl;
            return false;
        }
        
        // 解析节点信息
        Json::Value root;
        Json::Reader reader;
        
        if (!reader.parse(result.value, root)) {
            LOG_WARNING("解析持久化节点JSON失败: " + result.value);
            std::cout << "解析持久化节点信息失败" << std::endl;
            return false;
        }
        
        // 提取节点终端点和状态
        std::string endpoint = root["endpoint"].asString();
        NodeStatus nodeStatus = NodeStatus::UNKNOWN;
        if (root.isMember("status")) {
            nodeStatus = static_cast<NodeStatus>(root["status"].asInt());
        }
        
        // 检查节点是否为故障状态
        if (nodeStatus != NodeStatus::FAULT) {
            LOG_WARNING("节点 " + nodeId + " 不是故障状态，无需恢复");
            std::cout << "节点 " << nodeId << " 不是故障状态，无需恢复" << std::endl;
            return false;
        }
        
        LOG_INFO("发现故障节点: " + nodeId + ", endpoint: " + endpoint);
        std::cout << "发现故障节点: " << nodeId << ", endpoint: " << endpoint << std::endl;
        
        // 更新持久化节点状态为正常
        root["status"] = static_cast<int>(NodeStatus::FOLLOWER);
        if (root.isMember("faultTime")) {
            root.removeMember("faultTime");
        }
        Json::FastWriter writer;
        std::string updatedJson = writer.write(root);
        
        EtcdResult updateResult = etcdClient.put(persistentKey, updatedJson);
        if (!updateResult.success) {
            LOG_WARNING("更新持久化节点状态失败: " + updateResult.errorMessage);
            std::cout << "更新持久化节点状态失败: " << updateResult.errorMessage << std::endl;
            return false;
        }
        
        // 创建并启动节点
        LOG_INFO("正在恢复节点: " + nodeId + ", endpoint: " + endpoint);
        std::cout << "正在恢复节点: " << nodeId << ", endpoint: " << endpoint << std::endl;
        
        // 创建节点
        NodeManager* nodeManager = new NodeManager(m_etcdUrl, nodeId, endpoint);
        
        // 初始化节点
        if (!nodeManager->init()) {
            LOG_ERROR("初始化节点失败: " + nodeId);
            std::cout << "初始化节点失败: " << nodeId << std::endl;
            delete nodeManager;
            return false;
        }
        
        // 注册状态变更回调
        nodeManager->registerStatusCallback([nodeId](NodeStatus oldStatus, NodeStatus newStatus) {
            LOG_INFO("节点状态变更: " + nodeId + ", 从 " + std::to_string(static_cast<int>(oldStatus)) +
                    " 到 " + std::to_string(static_cast<int>(newStatus)));
            
            std::string oldStatusStr = "未知";
            std::string newStatusStr = "未知";
            
            switch (oldStatus) {
                case NodeStatus::FOLLOWER: oldStatusStr = "从节点"; break;
                case NodeStatus::LEADER: oldStatusStr = "主节点"; break;
                case NodeStatus::FAULT: oldStatusStr = "故障"; break;
                default: break;
            }
            
            switch (newStatus) {
                case NodeStatus::FOLLOWER: newStatusStr = "从节点"; break;
                case NodeStatus::LEADER: newStatusStr = "主节点"; break;
                case NodeStatus::FAULT: newStatusStr = "故障"; break;
                default: break;
            }
            
            std::cout << std::endl << "节点 " << nodeId << " 状态从 " 
                    << oldStatusStr << " 变为 " << newStatusStr << std::endl << "> ";
            std::cout.flush();
        });
        
        // 启动节点
        if (!nodeManager->start()) {
            LOG_ERROR("启动节点失败: " + nodeId);
            std::cout << "启动节点失败: " << nodeId << std::endl;
            delete nodeManager;
            return false;
        }
        
        // 保存节点
        m_nodes[nodeId] = nodeManager;
        
        LOG_INFO("成功恢复故障节点: " + nodeId);
        std::cout << "成功恢复故障节点 " << nodeId << std::endl;
        return true;
    } catch (const std::exception& e) {
        LOG_ERROR("恢复故障节点异常: " + std::string(e.what()));
        std::cout << "恢复故障节点时发生错误: " << e.what() << std::endl;
        return false;
    }
}